﻿using ASmile.Extend;
using ASmile.ORM.Cores;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ASmile.Mssql.AlterDBFile
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            txtConnStr.Text = Config.Settings.ConnStr;
        }

        class PhysicalList
        {
            public string name { set; get; }

            public string type_desc { set; get; }

            public string physical_name { set; get; }
        }

        List<PhysicalList> CurrPhysicalList { set; get; }

        DBContext DBMain { set; get; }

        void PrintLogs(string log)
        {
            txtLog.AppendText($"[{DateTime.Now:G}]：{log}\r\n");
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            DBMain = new DBContext(ORM.EmDbType.SQLServer, txtConnStr.Text);
            var dbName = txtDBName.Text;

            var sql = DBMain.CreateSqlBuilder();

            sql.AddSQLParam($@"
SELECT name, type_desc, physical_name
FROM sys.master_files
WHERE database_id = DB_ID('{dbName}');
");
            CurrPhysicalList = DBMain.Query(sql).ToList<PhysicalList>();

            for (int i = 0; i < CurrPhysicalList.Count; i++)
            {
                var item = CurrPhysicalList[i];
                if (i == 0)
                {
                    txtName1.Text = item.name;
                    txtName1New.Text = item.name;
                    txtName1File.Text = item.physical_name;
                }
                else if (i == 1)
                {
                    txtName2.Text = item.name;
                    txtName2New.Text = item.name;
                    txtName2File.Text = item.physical_name;
                }

                PrintLogs($"{item.name} {item.type_desc} {item.physical_name}");
            }
        }

        private void btnOFFLINE_Click(object sender, EventArgs e)
        {
            if (DBMain == null) return;
            var sqlText = $"ALTER DATABASE {txtDBName.Text} SET OFFLINE";
            PrintLogs(sqlText);
            var rr =
            DBMain.ExecSql(sql =>
            {
                sql.AddSQLParam(sqlText);
            });

            PrintLogs($"OFFLINE 完成，{rr.RowCount}");
        }

        private void btnOnLine_Click(object sender, EventArgs e)
        {
            if (DBMain == null) return;
            var sqlText = $"ALTER DATABASE {txtDBName.Text} SET ONLINE";
            PrintLogs(sqlText);
            var rr =
            DBMain.ExecSql(sql =>
            {
                sql.AddSQLParam(sqlText);
            });

            PrintLogs($"ONLINE 完成，{rr.RowCount}");
        }

        private void txtExec_Click(object sender, EventArgs e)
        {
            if (DBMain == null) return;
            btnOFFLINE_Click(sender, e);

            //ALTER DATABASE cr_peis MODIFY FILE (NAME = 'cr_peis', FILENAME = 'd:\sqldata2019\cr_peis.mdf');
            var dbName = txtDBName.Text;
            var sqlContent =
            DBMain.ExecSql(sql =>
            {
                sql.AddSQLText("\r\n");

                if (txtName1.Text.IsNotEmpty())
                {
                    sql.AddSQLText($"ALTER DATABASE {dbName} MODIFY FILE (NAME = '{txtName1.Text}', FILENAME = '{txtName1File.Text}');\r\n");

                }
                if (txtName2.Text.IsNotEmpty())
                {
                    sql.AddSQLText($"ALTER DATABASE {dbName} MODIFY FILE (NAME = '{txtName2.Text}', FILENAME = '{txtName2File.Text}');\r\n");
                }
                //PrintLogs(sql.SQLText);
            }).SqlContent;

            PrintLogs($"{sqlContent}\r\n 完成");

            btnName1Move_Click(sender, e);

            btnName2Move_Click(sender, e);

            btnOnLine_Click(sender, e);

            PrintLogs("完成");
        }

        private void btnName1Move_Click(object sender, EventArgs e)
        {
            var name = txtName1File.Text;
            var newFileName = txtName1File.Text;
            var oldFileName = CurrPhysicalList.Find(s => s.name == name).physical_name;
            if (oldFileName.StringEquals(newFileName))
            {
                return;
            }
            File.Move(oldFileName, newFileName);
            PrintLogs($"修改文件名完成，名称：{name} 原文件：{oldFileName}，新文件：{newFileName}");
        }

        private void btnName2Move_Click(object sender, EventArgs e)
        {
            var name = txtName2File.Text;
            var newFileName = txtName2File.Text;
            var oldFileName = CurrPhysicalList.Find(s => s.name == name).physical_name;
            if (oldFileName.StringEquals(newFileName))
            {
                return;
            }
            File.Move(oldFileName, newFileName);
            PrintLogs($"修改文件名完成，名称：{name} 路径：{txtName2File.Text}");
        }

        private void btnNam1Alter_Click(object sender, EventArgs e)
        {
            if (txtName1.Text.StringEquals(txtName1New.Text))
            {
                return;
            }
            var dbName = txtDBName.Text;
            DBMain.ExecSql(sql =>
            {
                sql.AddSQLText($"alter database {dbName} modify file(name={txtName1.Text}, newname={txtName1New.Text});");
            });

            PrintLogs($"{txtName1.Text} 改为：{txtName1New.Text}");

        }

        private void btnNam2Alter_Click(object sender, EventArgs e)
        {
            if (txtName2.Text.StringEquals(txtName2New.Text))
            {
                return;
            }
            var dbName = txtDBName.Text;
            DBMain.ExecSql(sql =>
            {
                sql.AddSQLText($"alter database {dbName} modify file(name={txtName2.Text}, newname={txtName2New.Text});");
            });

            PrintLogs($"{txtName2.Text} 改为：{txtName2New.Text}");
        }
    }
}
